﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace PersonaLibrary.Search
{
    public class StringSearchProperty : BaseSearchProperty
    {
        public StringSearchProperty(ParameterExpression parametr)
            : base(parametr)
        {
        }

        protected override List<string> CreateUnaryOperators()
        {
            return new List<string>
                       {
                           "Содержит",
                           "Несодержит",
                           "Начинается",
                           "Заканчивается",
						   "="
                       };
        }

        public override Expression CreateUnary()
        {
            Expression result = null;

            switch (SelectedUnaryOperator)
            {
                case "Содержит":
                    result = Property.NotNullTesting(Expression.Call(ResetPropertyRegistry(), typeof(string).GetMethod("Contains", new[] { typeof(string) }), ResetConstRegistry()));
                    break;
                case "Несодержит":
                    result = Property.NotNullTesting(Expression.Not(Expression.Call(ResetPropertyRegistry(), typeof(string).GetMethod("Contains", new[] { typeof(string) }), ResetConstRegistry())));
                    break;
                case "Начинается":
                    result = Property.NotNullTesting(Expression.Call(ResetPropertyRegistry(), typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), ResetConstRegistry()));
                    break;
                case "Заканчивается":
                    result = Property.NotNullTesting(Expression.Call(ResetPropertyRegistry(), typeof(string).GetMethod("EndsWith", new[] { typeof(string) }), ResetConstRegistry()));
                    break;
				case "=":
					result = Property.NotNullTesting(Expression.Call(ResetPropertyRegistry(), typeof(string).GetMethod("Equals", new[] { typeof(string) }), ResetConstRegistry()));
					break;
            }
            return result;
        }

		//private Expression nullTesting(Expression left)
		//{
		//    return Expression.NotEqual(left, Expression.Constant(null));
		//}

        private Expression ResetPropertyRegistry( )
        {
            Expression tmpExpression = Expression.Call(typeof (Convert).GetMethod("ToString", new[] {typeof(object)}), Property);
            return Expression.Call(tmpExpression, typeof(string).GetMethod("ToUpper", new Type[] { }));
        }

        private Expression ResetConstRegistry()
        {
			if (Constant == null)
				Constant = Expression.Constant(string.Empty);

            return Expression.Call(Constant, typeof(string).GetMethod("ToUpper", new Type[] { }));
        }
    }
}
